package cn.yunyichina.provider.base.service.impl;

import cn.yunyichina.provider.base.dao.PlatformExtensionDao;
import cn.yunyichina.provider.base.dao.PlatformExtensionUserDao;
import cn.yunyichina.provider.base.entity.OrgUserOpenid;
import cn.yunyichina.provider.base.entity.PlatformExtension;
import cn.yunyichina.provider.base.entity.PlatformExtensionUser;
import cn.yunyichina.provider.base.vo.PlatformQrcodeRequest;
import cn.yunyichina.provider.base.vo.PlatformQrcodeResponse;
import cn.yunyichina.provider.framework.annotation.validate.ValidateException;
import cn.yunyichina.provider.framework.annotation.validate.Validator;
import cn.yunyichina.provider.framework.common.PKGenerator;
import cn.yunyichina.provider.framework.dubbo.service.AlipayService;
import cn.yunyichina.provider.framework.dubbo.service.WechatPayService;
import cn.yunyichina.provider.framework.page.PageInfo;
import cn.yunyichina.provider.iface.entity.alipay.AlipayPublicQrcodeRequestVo;
import cn.yunyichina.provider.iface.entity.alipay.AlipayPublicQrcodeResponseVo;
import cn.yunyichina.provider.iface.entity.base.QrcodeRequestVo;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.iface.entity.common.ResponseObject;
import cn.yunyichina.provider.iface.entity.wechat.WechatPublicQrcodeResponseVo;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.commons.StringUtils;
import cn.yunyichina.utils.convert.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 二维码扫码管理平台
 * Created by Joe.zhou on 2017/11/27.
 */
@Service
public class ScanerPlatformServiceImpl {

    private static final Logger logger = LoggerFactory.getLogger(ScanerPlatformServiceImpl.class);

    @Autowired
    private PlatformExtensionDao platformExtensionDao;

    @Autowired
    private PlatformExtensionUserDao platformExtensionUserDao;

    @Autowired
    private OrgopenidServiceImpl orgopenidService;


    /**
     * 添加二维码关系信息、生成二维码
     * @param json
     * @interfaceName: yyt.base.scaner.platform.info.add
     * @return
     */
    public ResponseObject addScanerPlatformInfo(String json){
        logger.info("ScanerPlatformServiceImpl.addScanerPlatformInfo data={}", JsonUtils.toJsonString(json));
        ResponseObject response = new ResponseObject();
        PlatformQrcodeRequest request = JsonUtils.parseObject(json, PlatformQrcodeRequest.class);

        PlatformExtension extension = new PlatformExtension();
        extension.setId(PKGenerator.generateId());
        String exId = extension.getId();
        String openId = getOrgUserOpenId(request);

        String qrCodeUrl = "";
        String expireDate = "";
        try {
            if(request.getPayMode() == 1){ //微信
                Response wechatReps = getWechatQrcode(request, extension);
                if(Response.SUCCESS_CODE.equals(wechatReps.getResultCode())){
                    qrCodeUrl = wechatReps.getResult().replace("\"","");
                    if(request.getCodeType() == 1){ //临时
                        expireDate = getQrcodeExpireDate(DateUtils.dateToString(new Date()), request.getSeconds());
                    }else{ //永久
                        expireDate = "0";
                    }
                }else{
                    response.setResultCodeAndMessage(Response.FAILURE_CODE , wechatReps.getResultMessage());
                    return response;
                }
            }else{ //支付宝
                Response alipayReps = getAlipayQrcode(request, extension);
                if(Response.SUCCESS_CODE.equals(alipayReps.getResultCode())){
                    AlipayPublicQrcodeResponseVo alipayPublicQrcodeResponseVo = JsonUtils.parseObject(alipayReps.getResult(), AlipayPublicQrcodeResponseVo.class);
                    qrCodeUrl = alipayPublicQrcodeResponseVo.getQrCode();
                    expireDate = "0";
                }else{
                    response.setResultCodeAndMessage(Response.FAILURE_CODE , alipayReps.getResultMessage());
                    return response;
                }
            }
        } catch (Exception e) {
            logger.error("ScanerPlatformServiceImpl.addScanerPlatformInfo 生成二维码异常" ,e);
            response.setResultCodeAndMessage(Response.FAILURE_CODE,Response.FAILURE_MESSAGE);
            return response;
        }

        BeanUtils.copyProperties(request , extension);

        extension.setId(exId);
        extension.setOrgUserOpenId(openId);
        extension.setOrgScancodeUrl(qrCodeUrl);
        extension.setExpireSeconds(expireDate);
        extension.setCreatedTime(DateUtils.dateToString(new Date()));
        extension.setDefaultFlag((short) 1);
        platformExtensionDao.insert(extension);

        response.setResultCodeAndMessageAndResult(Response.SUCCESS_CODE , Response.SUCCESS_MESSAGE , JsonUtils.toJsonString(extension));

        return response;
    }


    /**
     * 获取推广人员openId
     * @return
     */
    public String getOrgUserOpenId(PlatformQrcodeRequest request){
        //获取推广人员openId
        OrgUserOpenid userOpenid = new OrgUserOpenid();
        userOpenid.setOrgUserId(request.getOrgUserId());
        userOpenid.setAppId(request.getPayAppId());
        userOpenid.setAppCode(request.getOrgAppCode());
        ResponseObject orgOpenReps = orgopenidService.getOrgOpenid(JsonUtils.toJsonString(userOpenid));
        if(Response.SUCCESS_CODE.equals(orgOpenReps.getResultCode())){
            List<OrgUserOpenid> orgUserOpenids = (List<OrgUserOpenid>) orgOpenReps.getResultObject();
            OrgUserOpenid openid = orgUserOpenids.get(0);
            return openid.getOpenId();
        }else{
            return null;
        }
    }



    /**
     * 获取临时二维码截止时间
     * @return
     */
    public String getQrcodeExpireDate(String createDate , Integer seconds){
        return DateUtils.getSecondsBetween(DateUtils.StringToDateYMD(createDate), seconds);
    }


    /**
     * 检查临时二维码是否失效
     * @return
     */
    public Boolean checkQrcodeExpireDate(String createDate , Integer seconds){

        Boolean flag;
        //获取有效使用时间截止日期提前一天
        String lastDate = DateUtils.getSecondsBetween(DateUtils.StringToDateYMD(createDate), seconds);
        String lastDateYesterday = DateUtils.getDaysBetween(DateUtils.StringToDateYMD(lastDate), -1);
        logger.info("获取到有效使用时间截止日期：" + lastDate +",有效使用时间截止提前一天日期：" + lastDateYesterday);
        if(new Date().getTime() > DateUtils.StringToDateYMD(lastDateYesterday).getTime()){
            flag = false;
        }else{
            flag = true;
        }

        return flag;
    }


    /**
     * 查询二维码推广人关系信息
     * @param json
     * @interfaceName: yyt.base.scaner.platform.info.get
     * @return
     */
    public Response getScanerPlatformInfo(String json){
        logger.info("ScanerPlatformServiceImpl.getScanerPlatformInfo data={}", JsonUtils.toJsonString(json));
        Response response = new Response();
        PlatformExtension extension = JsonUtils.parseObject(json, PlatformExtension.class);
        if(extension != null){
            List<String> orderColumns = new ArrayList<String>();
            orderColumns.add("created_time");
            Map<String, Object> map = new HashMap<String, Object>();
            PageInfo pageInfo = new PageInfo();
            pageInfo.setPageNum(extension.getPageNum());
            pageInfo.setPageSize(extension.getPageSize());

            long extensionsCount = platformExtensionDao.selectCount(extension);
            pageInfo.setTotal(extensionsCount);
            pageInfo.setPages((pageInfo.getTotal().intValue() + pageInfo.getPageSize() - 1) / pageInfo.getPageSize());
            map.put("page_info" , pageInfo);
            List<PlatformExtension> select = platformExtensionDao.select(extension , null , orderColumns , false , pageInfo);
            map.put("extensions" , select);
            if(select.size() > 0){
                response.setResultCodeAndMessageAndResult(Response.SUCCESS_CODE , Response.SUCCESS_MESSAGE , JsonUtils.toJsonString(map));
            }else{
                response.setResultCodeAndMessage(Response.FAILURE_CODE , "查无结果");
            }
        }

        return response;
    }



    /**
     * 根据条件查询二维码推广人关系信息
     * @param json
     * @interfaceName: yyt.base.scaner.platform.info.select
     * @return
     */
    public Response selectScanerPlatformInfo(String json){
        logger.info("ScanerPlatformServiceImpl.selectScanerPlatformInfo data={}", JsonUtils.toJsonString(json));
        Response response = new Response();
        PlatformExtension extension = JsonUtils.parseObject(json, PlatformExtension.class);
        if(extension != null){
            List<PlatformExtension> select = platformExtensionDao.select(extension);
            if(select.size() > 0){
                response.setResultCodeAndMessageAndResult(Response.SUCCESS_CODE , Response.SUCCESS_MESSAGE , JsonUtils.toJsonString(select));
            }else{
                response.setResultCodeAndMessage(Response.FAILURE_CODE , "查无结果");
            }
        }

        return response;
    }



    /**
     * 添加用户与推广人员关系
     * @param json
     * @interfaceName: yyt.base.scaner.platform.user.add
     * @return
     */
    public ResponseObject addScanerPlatformUser(String json){
        logger.info("ScanerPlatformServiceImpl.addQrcodePlatformUser data={}", JsonUtils.toJsonString(json));
        ResponseObject response = new ResponseObject();
        PlatformExtensionUser extension = JsonUtils.parseObject(json, PlatformExtensionUser.class);
        if(extension != null){
            platformExtensionUserDao.insert(extension);
        }else{
            logger.info("ScanerPlatformServiceImpl.addQrcodePlatformUser 实体extension 为空！");
        }

        response.setResultCodeAndMessage(Response.SUCCESS_CODE , Response.SUCCESS_MESSAGE);

        return response;
    }


    /**
     * 修改用户与推广人员关系
     * @param json
     * @interfaceName: yyt.base.scaner.platform.user.update
     * @return
     */
    public ResponseObject updateScanerPlatformUser(String json){
        logger.info("ScanerPlatformServiceImpl.updateScanerPlatformUser data={}", JsonUtils.toJsonString(json));
        ResponseObject response = new ResponseObject();
        PlatformExtension extension = JsonUtils.parseObject(json, PlatformExtension.class);
        if(extension != null){
            platformExtensionDao.update(extension);
        }else{
            logger.info("ScanerPlatformServiceImpl.updateScanerPlatformUser 实体extension 为空！");
        }
        response.setResultCodeAndMessage(Response.SUCCESS_CODE , Response.SUCCESS_MESSAGE);

        return response;
    }



    /**
     * 获取微信二维码
     * @param request
     * @return
     */
    public Response getWechatQrcode(PlatformQrcodeRequest request , PlatformExtension platformExtension){
        logger.info("ScanerPlatformServiceImpl.getWechatQrcode data={}", JsonUtils.toJsonString(request));

        QrcodeRequestVo qrcodeRequestVo = new QrcodeRequestVo();
        qrcodeRequestVo.setAppId(request.getPayAppId());
        qrcodeRequestVo.setCodeType(request.getCodeType());
        qrcodeRequestVo.setExtension_id(platformExtension.getId());
        qrcodeRequestVo.setSeconds(request.getSeconds());

        return WechatPayService.callHumpFromInternal("yyt.wechatpay.wechat.public.qrcode.general.create", JsonUtils.toJsonString(qrcodeRequestVo));
    }



    /**
     * 获取支付宝二维码
     * @param request
     * @return
     */
    public Response getAlipayQrcode(PlatformQrcodeRequest request , PlatformExtension platformExtension){
        logger.info("ScanerPlatformServiceImpl.getAlipayQrcode data={}", JsonUtils.toJsonString(request));
        AlipayPublicQrcodeRequestVo requestVo = new AlipayPublicQrcodeRequestVo();
        requestVo.setAppId(request.getPayAppId());
        requestVo.setId(platformExtension.getId());
        return AlipayService.callHumpFromInternal("yyt.alipay.alipay.public.qrcode.create", JsonUtils.toJsonString(requestVo));
    }

}
